package com.hong.spring.dao;

import com.hong.spring.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Auther: csh
 * @Date: 2020/8/18 15:04
 * @Description:用户dao层
 */
@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     *
     * 功能描述:查询总条数
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/18 15:31
     */
    public List<User> findAllUserList(){
        String sql = "select id,user_name as username,age from user";
        List<User> userList = jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }
    /**
     *
     * 功能描述:获取总数
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/18 15:30
     */
    public int findAllTotal(){
        String sql = "select count(1) from user";
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }
    /**
     *
     * 功能描述:更新
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/18 15:30
     */
    public int update(User user){
        if(user==null || user.getId()==null){
            return 0;
        }
        String sql = "update user set user_name =?,age=? where id=?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper(User.class);
        return jdbcTemplate.update(sql,user.getUsername(),user.getAge(),user.getId());
    }

    public int save(User user){
        if(user==null){
            return 0;
        }
        String sql = "insert into user(user_name,age) values(?,?)";
        return jdbcTemplate.update(sql,user.getUsername(),user.getAge());
    }

    public User findById(int id) {
        String sql = "select * from user where id=?";

        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class), id);
    }

}
